from flask import Flask, request, jsonify
import os, requests, jsonpath

app = Flask(__name__)


def save_uploaded_photo(photo):
    upload_dir = 'uploads'
    os.makedirs(upload_dir, exist_ok=True)

    photo_path = os.path.join(upload_dir, photo.filename)
    photo.save(photo_path)

    url = "http://localhost:8000/api/v1/recognition/recognize"

    api_key = "5c85256a-b627-4854-bc60-7a7918d0967c"

    headers = {
        'x-api-key': api_key,
    }

    files = {
        'file': (photo_path, open(photo_path, 'rb'), 'image/jpeg'),
    }

    response = requests.post(url, headers=headers, files=files)

    result1 = response.json()

    subject_list = jsonpath.jsonpath(result1, '$..subject')
    similarity_list = jsonpath.jsonpath(result1, '$..similarity')

    print(subject_list, similarity_list)

    def send_wechat(msg):
        token = '2cc51f9611034e5cb9614c5b948d3640'
        title = '人脸识别结果'
        content = msg
        template = 'html'
        url = f"https://www.pushplus.plus/send?token={token}&title={title}&content={content}&template={template}"
        print(url)
        r = requests.get(url=url)
        print(r.text)

    if __name__ == '__main__':

        if similarity_list[0] > 0.8:
            msg = subject_list[0]
            send_wechat(msg)
        else:
            msg = '陌生人'
            send_wechat(msg)

    return photo_path


@app.route('/upload_photo', methods=['POST'])
def upload_photo():
    if 'photo' not in request.files:
        return jsonify({'error': 'No photo provided'}), 400

    photo = request.files['photo']

    if photo.filename == '':
        return jsonify({'error': 'Empty filename provided'}), 400

    saved_photo_path = save_uploaded_photo(photo)

    return jsonify({'message': '图片已成功下载', 'photo_path': saved_photo_path}), 200


if __name__ == '__main__':
    app.run()
